package com.yueke.gemini.mongodb;


import com.mongodb.*;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 自己编写的java操作mongdb数据库的查询类
 *
 * @author mengzhang6
 * @since 2016/07/27
 * @version 1.0
 *
 */
public class MongoDBTools {

    // 单例模式
    private static MongoDBTools UTILS = new MongoDBTools();

    public static MongoDBTools getInstance() {
        return UTILS;
    }

    private Mongo mongo;
    private DB db;
    private DBCollection coll;
    private List<DBObject> dbos;
    private JSONArray jsonArray;

    /**
     * 单条件查询
     *
     * @param host
     *            主机地址
     * @param port
     *            端口号
     * @param dbName
     *            数据库名称
     * @param collectionName
     *            集合名称
     * @param key
     *            键
     * @param value
     *            值
     * @return JSONArray
     */
    public JSONArray getJSONArray(String host, int port, String dbName,
                                  String collectionName, String key, Object value) {
        try {
            // 连接数据库
            // Mongo mongo = new Mongo("192.168.57.49", 27017);
            mongo = new Mongo(host, port);
            // 打开数据库
            db = mongo.getDB(dbName);
            // 取得集合xxx(若：xxx不存在，mongodb将自动创建该集合)
            coll = db.getCollection(collectionName);
            dbos = coll.find(new BasicDBObject(key, value)).toArray();
            jsonArray = new JSONArray(String.valueOf(dbos));
        } catch (MongoException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (mongo != null)
                mongo.close();
            mongo = null;
            db = null;
            coll = null;
            dbos = null;
        }
        return jsonArray;
    }

    public JSONArray getJSONArray(String host, int port, String dbName,
                                  String collectionName, String key, Object value, String key2,
                                  Object value2, String type) {
        try {
            mongo = new Mongo(host, port);
            db = mongo.getDB(dbName);
            coll = db.getCollection(collectionName);
            BasicDBObject b1 = new BasicDBObject(key, value);
            BasicDBObject b2 = new BasicDBObject(key2, value2);
            // 混合条件
            BasicDBObject unitObject = new BasicDBObject().append(
                    QueryOperators.AND, new BasicDBObject[] { b1, b2 });
            // 一般不用OR，所以默认AND
            if (type.equals("OR"))
                unitObject = new BasicDBObject().append(QueryOperators.OR,
                        new BasicDBObject[] { b1, b2 });
            // 查询
            List<DBObject> dbos = coll.find(unitObject).toArray();
            JSONArray jsonArray = new JSONArray(String.valueOf(dbos));
        } catch (MongoException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (mongo != null)
                mongo.close();
            mongo = null;
            db = null;
            coll = null;
            dbos = null;
        }
        return jsonArray;
    }

    private MongoClient mongoClient;
    private MongoDatabase mongoDatabase;
    private MongoCollection<?> mongoCollection;
    private FindIterable<?> findIterable;
    private MongoCursor<?> cursor;

    /**
     * 单条件查询
     *
     * @param host
     * @param port
     * @param dbName
     * @param collectionName
     * @param key
     * @param value
     * @return org.bson.Document集合
     */
    public List<Document> getDocumentList(String host, int port, String dbName,
                                          String collectionName, String key, Object value) {
        List<Document> documentList = new ArrayList<Document>();
        try {
            mongoClient = new MongoClient(host, port);
            mongoDatabase = mongoClient.getDatabase(dbName);
            mongoCollection = mongoDatabase.getCollection(collectionName);
            BasicDBObject basicDBObject = new BasicDBObject(key, value);
            findIterable = mongoCollection.find(basicDBObject);
            cursor = findIterable.iterator();
            while (cursor.hasNext()) {
                Document document = (Document) cursor.next();
                documentList.add(document);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cursor.close();
            mongoClient.close();
        }
        return documentList;
    }

    /**
     * 双条件查询
     *
     * @param host
     * @param port
     * @param dbName
     * @param collectionName
     * @param key
     * @param value
     * @param key2
     * @param value2
     * @param type
     *            AND 或 OR
     * @return
     */
    public List<Document> getDocumentList(String host, int port, String dbName,
                                          String collectionName, String key, Object value, String key2,
                                          Object value2, String type) {
        List<Document> documentList = new ArrayList<Document>();
        try {
            mongoClient = new MongoClient(host, port);
            mongoDatabase = mongoClient.getDatabase(dbName);
            mongoCollection = mongoDatabase.getCollection(collectionName);
            BasicDBObject basicDBObject = new BasicDBObject(key, value);
            BasicDBObject basicDBObject2 = new BasicDBObject(key2, value2);
            BasicDBObject unitObject = new BasicDBObject().append(
                    QueryOperators.AND, new BasicDBObject[] { basicDBObject,
                            basicDBObject2 });
            // 一般不用OR，所以默认AND
            if (type.equals("OR"))
                unitObject = new BasicDBObject().append(QueryOperators.OR,
                        new BasicDBObject[] { basicDBObject, basicDBObject2 });
            findIterable = mongoCollection.find(unitObject);
            cursor = findIterable.iterator();
            while (cursor.hasNext()) {
                Document document = (Document) cursor.next();
                documentList.add(document);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cursor.close();
            mongoClient.close();
        }
        return documentList;
    }

    /**
     * 多条件查询
     *
     * @param host
     * @param port
     * @param dbName
     *            数据库
     * @param collectionName
     *            集合名
     * @param keyValues
     *            Map<String, Object>集合
     * @param type
     *            OR 或 AND
     * @return
     */
    public List<Document> getDocumentList(String host, int port, String dbName,
                                          String collectionName, Map<String, Object> keyValues, String type) {
        List<Document> documentList = new ArrayList<Document>();
        try {
            mongoClient = new MongoClient(host, port);
            mongoDatabase = mongoClient.getDatabase(dbName);
            mongoCollection = mongoDatabase.getCollection(collectionName);

            List<BasicDBObject> basicDBObjectList = new ArrayList<BasicDBObject>();
            for (String key : keyValues.keySet()) {
                BasicDBObject b = new BasicDBObject(key, keyValues.get(key));
                basicDBObjectList.add(b);
            }

            BasicDBObject unitObject = new BasicDBObject().append(
                    QueryOperators.AND, basicDBObjectList);
            // 一般不用OR，所以默认AND
            if (type.equals("OR"))
                unitObject = new BasicDBObject().append(QueryOperators.OR,
                        basicDBObjectList);
            findIterable = mongoCollection.find(unitObject);
            cursor = findIterable.iterator();
            while (cursor.hasNext()) {
                Document document = (Document) cursor.next();
                documentList.add(document);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cursor.close();
            mongoClient.close();
        }
        return documentList;
    }

}

